﻿using AutoMapper;
using HuaweiCloud.Dotnet.Samples.Common;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Dtos;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Entities;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Specification;
using Volo.Abp.Guids;

namespace HuaweiCloud.Dotnet.Samples.ESports.Main.Service
{
    public class PointsService : CrudApplicationServiceBase<Points, UpdatePointsDto, UpdatePointsDto, PointsDto>
        , IPointsService
    {
        private readonly IGuidGenerator _idGenerator;
        public PointsService(IRepository<Points> repository
            , IMapper mapper
            , IGuidGenerator idGenerator) : base(repository, mapper)
        {
            _idGenerator = idGenerator;
        }

        public async Task AddScoresAsync(Guid userId, int scores, CancellationToken token = default)
        {
            var info = await _repository.FirstOrDefaultAsync(new PointsSpecification(userId), token);
            if (info == null)
                await _repository.AddAsync(new Points(_idGenerator.Create(), userId, scores), token);
            else
            {
                info.Scores += scores;
                await _repository.UpdateAsync(info, token);
            }
        }

        public async Task<PointsDto> GetScoresByUserIdAsync(Guid userId, CancellationToken token = default)
        {
            var info = await _repository.FirstOrDefaultAsync(new PointsSpecification(userId), token);
            if (info == null)
                return new PointsDto();
            else
                return _mapper.Map<PointsDto>(info);
        }
    }
}
